<template>
<div class="home-container" ref="scrollContainer">
    <!-- 标签 -->
    <div class="fixed-tabs">
        <div class="tab-wrap">
            <div class="tabs">
                <div v-for="(item, index) in tabs" :key="index" 
                    class="tab" :class="{ active: activeTabIndex === index }"
                    @click="changeTab(item, index)">
                    {{ item }}
                </div>
            </div>
        </div>
    </div>

    <!-- 内容 -->
    <PostList v-show="activeTabName === '推荐'" :tab="'推荐'" ref="recommendPostListRef" />
    <PostList v-show="activeTabName === '关注'" :tab="'关注'" ref="followPostListRef" />
    
</div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onActivated, onDeactivated, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import PostList from '@/components/PostList.vue'
import { UserInfoStore } from '@/stores/userInfoStore'
import { TipStore } from '@/stores/tipStore'

const user_Store = UserInfoStore()
const tip_Store = TipStore()

const tabs = ref(['推荐', '关注']) // 标签
const activeTabIndex = ref(0) // 当前激活的标签索引
const activeTabName = computed(() => {
    return tabs.value[activeTabIndex.value]
})

// 切换标签
const changeTab = async(item, index) => {
    if(item === '关注'){
        if(!user_Store.userInfo.id){
            tip_Store.warningTip('请先登录')
            return
        }
        if (followPostListRef.value) {
            followPostListRef.value.initData(); // 触发[关注]数据加载
        }
    }
    
    // 保存当前标签的滚动位置
    if (scrollContainer.value) {
        scrollPositions.value[activeTabName.value] = scrollContainer.value.scrollTop;
        console.log(`保存${activeTabName.value}标签的滚动位置:`, scrollContainer.value.scrollTop);
    }
    
    activeTabIndex.value = index
    
    // 恢复新标签的滚动位置
    await nextTick(); // 等待DOM更新
    if (scrollContainer.value) {
        // 如果新标签有保存的滚动位置，则恢复它
        if (scrollPositions.value && scrollPositions.value[activeTabName.value] !== undefined) {
            const savedPosition = scrollPositions.value[activeTabName.value];
            scrollContainer.value.scrollTop = savedPosition;
            // console.log(`恢复${activeTabName.value}标签的滚动位置:`, savedPosition);
        } else {
            // 如果是新标签第一次访问，则滚动到顶部
            scrollContainer.value.scrollTop = 0;
            // console.log(`${activeTabName.value}标签第一次访问，滚动到顶部`);
        }
    }
}


// 恢复滚动位置相关
const scrollContainer = ref(null)
const scrollPositions = ref({}) // 存储不同标签的滚动位置
const savedScrollPosition = ref(0); // 保存滚动条位置
const recommendPostListRef = ref(null) // 推荐标签的PostList组件引用
const followPostListRef = ref(null) // 关注标签的PostList组件引用
onBeforeRouteLeave((to, from, next)=> {
    //console.log('路由钩子打印时间：', new Date().getMilliseconds());
    //跳转路由之前记录滚动条位置 
    if (scrollContainer.value) {
        savedScrollPosition.value = scrollContainer.value.scrollTop;
        console.log('Home离开前记录位置--:', savedScrollPosition.value);
    }
    next(); //允许跳转
})


onMounted(async() => {
    console.log('Home 被挂载了！')
});


//当前组件被用keep-alive缓存了，会有两个新的生命周期函数
onActivated(() => {
    //console.log("激活主页面")
    if (scrollContainer.value && savedScrollPosition.value > 0) {
        scrollContainer.value.scrollTop = savedScrollPosition.value;
        console.log('Home--恢复滚动位置:', savedScrollPosition.value);
    }
});

onDeactivated(() => {
    //console.log('失活打印时间:', new Date().getMilliseconds());
    //console.log("离开主页面")
});


</script>

<style lang="scss" scoped>
.home-container {
    position: relative;
    max-width: 1200px;
    min-width: 300px;
    width: 100%;
    height: calc(100vh - 180px); /* 使用视口高度减去顶部和底部元素的高度 */
    margin-top: 113px; /* 增加上边距以避免内容被固定标签遮挡 */
    margin-bottom: 70px;
    margin-left: auto;
    margin-right: auto;
    padding: 0px 8px 20px 8px;
    overflow-y: auto; /* 允许垂直滚动 */
    scrollbar-width: none; /* 隐藏Firefox滚动条 */
    -ms-overflow-style: none; /* 隐藏IE滚动条 */
}

.fixed-tabs {
    position: fixed;
    top: 68px;
    left: 0;
    right: 0;
    z-index: 100;
    background-color: #fff; /* 确保背景不透明 */
    border-top: 1px #ededed solid;
    border-bottom: 1px #ededed solid;
    display: flex;
    justify-content: center;
}

.tab-wrap{
    width: 100%;
    max-width: 1200px
}

.tabs {
    display: flex;
    gap: 20px;
    flex-wrap: nowrap; /* 防止标签换行 */
    overflow-x: auto; /* 允许水平滚动 */
    white-space: nowrap; /* 防止文本换行 */
    padding: 0 20px;
    -webkit-overflow-scrolling: touch; /* 在iOS上提供平滑滚动 */
    scrollbar-width: none; /* 隐藏Firefox滚动条 */
    -ms-overflow-style: none; /* 隐藏IE滚动条 */
}

.tab {
    padding: 10px 5px;
    cursor: pointer;
    color: #666;
    border-bottom: 2px solid transparent;
    transition: all 0.3s;
    flex-shrink: 0; /* 防止标签被压缩 */
    min-width: 40px; /* 设置最小宽度 */
    text-align: center; /* 文本居中 */
}

.tab.active {
    color: #ff6b6b;
    border-bottom-color: #ff6b6b;
}

</style>